<template>
  <div ref="editorRef" class="editor-main"></div>
</template>

<script lang="ts" setup>
import { basicSetup, EditorView } from "codemirror";
import { EditorState } from "@codemirror/state";
import { javascript } from "@codemirror/lang-javascript";
import { onMounted, ref, watch } from "vue";
import { stringFormat } from "@/utils/utils";
let props = defineProps({
  value: {
    type: Object,
    required: false,
    default: () => {
      return {};
    }
  }
});
const editorRef = ref();
const editorView = ref();
const initEditor = () => {
  const startState = EditorState.create({
    doc: "欢迎使用！\n",
    extensions: [basicSetup, javascript(), EditorView.editable.of(false), EditorState.readOnly.of(true)]
  });
  if (editorRef.value) {
    editorView.value = new EditorView({
      state: startState,
      parent: editorRef.value
    });
  }
};
watch(
  () => props.value,
  (data) => {
    if (data && data.message !== undefined) {
      const message = `[${data.level}] ${stringFormat(data.message, data.variables)}` + "\n";
      editorView.value.dispatch({
        changes: {
          from: editorView.value.state.doc.length,
          to: editorView.value.state.doc.length,
          insert: message
        }
      });
    }
  }
);
// onMounted生命周期可以保证读取到dom元素
onMounted(() => {
  initEditor();
});
</script>

<style lang="scss" scoped>
.editor-main {
  width: 100%;
  height: 100%;
  overflow: auto;
}
</style>
